#!/usr/bin/env python
#
#   
#   Author: Tim


import threading
import serial

from Keymap import keymap


class SerialReader(threading.Thread):
    def __init__(self, port, baud):
        threading.Thread.__init__(self)
        self.running = True
        self.port = port
        self.baud = baud
        self.ser = serial.Serial(self.port, self.baud)
        
    def run(self):
        while self.running:
            line = str(self.ser.readline(), "UTF-8")
            if line.find(":") == -1:
                print(line)
            else:
                keyevent = line.split(":")
                protocol = keyevent[0]
                address = keyevent[1]
                command = keyevent[2]
                flag = "pressed" if (keyevent[3][0] == "0") else "hold"
                
                if protocol in keymap.keys():
                    # keymap known for protocol
                    print(keymap.get(protocol).get(command)+" "+flag)   
                else:
                    # unknown keymap
                    print("no keymap - P:"+protocol+" A:"+address+" C:"+command+" F:"+flag) 
                
            
    def stop(self):
        self.running = False
            
            
sr = SerialReader("/dev/ttyACM0", 115200)
sr.start()
